import os
import wsgiref.handlers
import urllib

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from google.appengine.api import users

from Img import Img

import logging
class mainpage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        login_url = users.create_login_url(urllib.unquote_plus(self.request.uri))
        templatedic = { 'user': user,
                        'host_url': self.request.host_url,
                        'login_url': login_url}
        
        path = os.path.join(os.path.dirname(__file__), 'template', 'index.html')
        self.response.out.write(template.render(path, templatedic))
        return

class borrowimg(webapp.RequestHandler):
    def get(self):
        #request.path_qs      #/borrow/http%3A//www.sgei.com%252Ffjalg.asp%253Ffjao%253Dtwr?ffff=7
        imgurl = self.request.path_qs[len('/borrow/'):]
        imgurl = urllib.unquote_plus(imgurl)
        heads = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT)',
                   'referer' : webapp.Request.blank(imgurl).host_url}
        i = 0
        while i<2:
            i=i+1
#            self.response.out.write(imgurl)
#            self.response.out.flush()
            resp = urlfetch.fetch(imgurl,
                       method=urlfetch.GET,
                       headers=heads)
#            self.response.out.write('\n--------------------------------\n')
#            self.response.out.write('\n'.join([k + ':' + resp.headers[k] for k in resp.headers.keys()]))
#            self.response.out.write('\n--------------------------------\n')
#            self.response.out.write(resp.content)
            if not resp.status_code in [301,302,307]:
                break
            imgurl = resp.headers['location']
            

        if resp.status_code == 200:
            self.response.headers['Content-Type'] = resp.headers['Content-Type']
#            self.response.out.write('\n'.join([k + ':' + resp.headers[k] for k in resp.headers.keys()]))
        self.response.out.write(resp.content)
        
        
class redirect(webapp.RequestHandler):
    def get(self):
        #request.path_qs      #/redirect/http%3A//www.sgei.com%252Ffjalg.asp%253Ffjao%253Dtwr?ffff=7
        imgurl = self.request.path_qs[len('/redirect/'):]
        imgurl = urllib.unquote_plus(imgurl)
        self.redirect(imgurl)

def main():
    application = webapp.WSGIApplication(
                           [('/',mainpage),
                            ('/index.html',mainpage),
                            ('/borrow/.*', borrowimg),
                           ('/redirect/.*', redirect)],
                           debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()

